from datetime import datetime, timedelta

from flask import current_app, g
from flask_restful import Resource
from flask_restful.reqparse import RequestParser
from utils import parser
from utils.jwt_util import generate_jwt


class AuthorizationResource(Resource):

    """认证"""
    def _generate_tokens(self, user_id, is_refresh=True):
        """
        生成token和refresh
        :param user_id: 用户id
        :param refresh: refresh_token
        :return: token, refresh_token
        """
        # jwt
        now = datetime.utcnow()
        secret = current_app.config['JWT_SECRET']
        expiry = now + timedelta(hours=current_app.config['JWT_EXPIRY_HOURS'])
        token = generate_jwt({'user_id': user_id, 'is_refresh_token': False}, expiry, secret)

        if is_refresh:
            refresh_exipry = now + timedelta(days=current_app.config['JWT_REFRESH_DAYS'])
            refresh_token = generate_jwt({'user_id': user_id, 'is_refresh_token': True}, refresh_exipry, secret)
        else:
            refresh_token = None

        return token, refresh_token

    def post(self):
        """
        登陆并返回token
        """
        # 1.获取请求参数
        json_parser = RequestParser()
        json_parser.add_argument('mobile', type=parser.mobile, required=True)
        json_parser.add_argument('code', type=parser.regex(r'^\d{6}$'), required=True)
        args = json_parser.parse_args()
        mobile = args.mobile
        code = args.code

        # 2.从redis中获取验证码并比对
        key = 'app:code:{}'.format(mobile)

        # 3.查询或保存用户

        # 4.生成token
        token, refresh_token = self._generate_tokens("123456")
        return {'token': token, 'refresh_token': refresh_token}, 201


    def put(self):
        """
        刷新token
        """
        if g.user_id is not None and g.is_refresh_token is True:
            token, refresh_token = self._generate_tokens(g.user_id, is_refresh=True)
            return {'token':token}
        else:
            return {'message': 'Invalid refresh token'}, 403









